import Taro from "@tarojs/taro";
import {
  getTokenInfo,
  setToken,
  setTokenInfo,
  getToken,
} from "@/utils/storage";
import { httpClient } from "./index";
/**
 * 简单复制对象
 * 从resource->target
 */
export const copyObject = function copyObject(target, resource) {
  if (typeof target === "undefined") {
    return resource;
  }
  if (typeof resource === "undefined" || resource === null) {
    return target;
  }
  // eslint-disable-next-line no-unused-vars
  for (const key in resource) {
    if (resource.hasOwnProperty(key)) {
      if (resource[key] === null || resource[key] === "undefined") continue;
      target[key] = resource[key];
    }
  }
  return target;
};

const Toast = {
  fail: (title) => {
    $TzNotify.danger(title + "");
  },
};
/**
 *刷新token
 * @returns promise
 */
export const refreshTokenInfo = () => {
  const { refreshToken } = getTokenInfo();
  if (!refreshToken) return;
  const refreshUrl = "/wx/refreshToken?refreshToken=" + refreshToken;
  //不要带token 就把token设置成none
  const option = {
    url: refreshUrl,
    method: "POST",
    header: { Authorization: "none" },
  };

  return httpClient(option)
    .then((res) => {
      setTokenInfo(res.data);
      return setToken(res.data.accessToken);
    })
    .catch(() => {
      Taro.reLaunch({
        url: "/pages/login/index",
      });
      Taro.showToast({
        title: "账号过期，请重新登陆！",
        icon: "none",
        duration: 2000,
      });
      return Promise.reject();
    });
};

let locked = false;
/**
 * 处理登录验证过期
 */
const handleUnauthorized = async () => {
  const { refreshToken, now } = getTokenInfo();
  const isExpire = 28 * 12 * 3600 - parseInt((Date.now() - now) / 1000) <= 0;
  //如果有refreshToken并且没有过期
  if (refreshToken && !isExpire && getToken()) {
    //刷新token
    if (locked) return;
    locked = true;
    await refreshTokenInfo();
    locked = false;
    //重定向当前页
    const url = Taro.getCurrentInstance().router.path.split("?")[0];
    const tabPage = ["/pages/home/index", "/pages/mine/index"];
    //如果是tabbar页面
    if (tabPage.includes(url)) {
      Taro.reLaunch({ url });
      return;
    }
    Taro.redirectTo({ url });
    return;
  }
  Taro.reLaunch({
    url: "/pages/login/index",
  });
  Taro.showToast({
    title: "账号过期，请重新登陆！",
    icon: "none",
    duration: 2000,
  });
};

/**
 *网络错误状态处理
 */
export const errHandler = (error) => {
  console.log(error);
  switch (error.statusCode || error.status) {
    case 401:
      // token失效到登陆页
      if (error.data?.code === 401) {
        handleUnauthorized(error);
        return;
      }
      // Toast.fail(error.data?.msg || error.message);
      break;
    case 403:
      Toast.fail(error.message || "403异常");
      break;
    case 404:
      Toast.fail(error.message || "404异常");
      break;
    case 422:
      Toast.fail("请求参数错误");
      break;
    case 426:
      Toast.fail(error?.data.msg || "请求参数错误");
      break;
    case 428:
      Toast.fail(error?.data.msg || "无效的身份");
      break;
    case 500: {
      const url = error.url || "";
      Toast.fail(url + "-服务器无响应(500)");
      break;
    }

    default:
      Toast.fail(error.msg || "未知的情况");
      break;
  }
};
